package com.nsxy.manager.common.utils;

import java.util.Calendar;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.nsxy.manager.login.beans.LoginLog;
import com.nsxy.manager.login.service.ILoginLogService;
import com.nsxy.manager.user.beans.Account;

/**
 * 校验
 * @author 潜行的青衣
 * @see
 */
public class PasswordCredentialsMatcher implements CredentialsMatcher {

	private PasswordEncoder passwordEncoder;
	
	@Resource
	private ILoginLogService loginLogService;
	
	public PasswordCredentialsMatcher() {}
	
	public PasswordCredentialsMatcher(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.authc.credential.CredentialsMatcher#doCredentialsMatch(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.authc.AuthenticationInfo)
	 */
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		boolean isMatch = this.passwordEncoder.matches(new String((char[]) token.getCredentials()), (String) info.getCredentials());
		//登录日志
		LoginLog log = new LoginLog();
		Account account = (Account) info.getPrincipals().getPrimaryPrincipal();
		log.setAccId(account.getId());
		log.setLogintime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
		log.setStatus(isMatch ? LoginLog.STATUS_SUCCESS : LoginLog.STATUS_FAILURE);
		this.loginLogService.save(log);
		return isMatch;
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

}
